package priv.wangy.micro.common.aop.encrypt;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import priv.wangy.micro.common.utils.EncryptType;
import priv.wangy.micro.common.utils.EncryptUtil;

import java.lang.reflect.Field;

/**
 *@author wangy
 *@since 2024/9/10
 */


@Slf4j
@Aspect
@Component
public class EncryptAspect {

    //拦截需加密注解
    @Pointcut("@annotation(com.whminwei.common.encrypt.Encryption)")
    public void point() {

    }

    @Around("point()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //加密
        encrypt(joinPoint);
        return joinPoint.proceed();
    }

    public void encrypt(ProceedingJoinPoint joinPoint) {
        Object[] objects;
        try {
            objects = joinPoint.getArgs();
            for (Object object : objects) {
                Field[] fields = object.getClass().getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    if (field.isAnnotationPresent(EncryptField.class)) {
                        if (field.get(object) != null) {
                            String realValue = (String) field.get(object);
                            EncryptType type = field.getAnnotation(EncryptField.class).value();
                            String encrypt = EncryptUtil.encrypt(realValue, type);
                            field.set(object, encrypt);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

}